import { useState, useEffect, useRef } from 'react';
import { Button, Tooltip, Space, Modal, Form, Checkbox, Input, InputNumber, message } from 'antd';
import { ExclamationCircleOutlined, BulbOutlined } from '@ant-design/icons';
import { connect, FormattedMessage, useIntl } from 'umi';
import request from '@/utils/request';
import { WhseSelect, WhseBinSelect } from '@/components/FormItemSelect';
import QuerySelect from '@/components/QuerySelect';

const { confirm } = Modal;
const apiURL = '/api/services/app/ShipDtl/';

const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<any>({});
  const [freshNum, setFreshNum] = useState(1);
  const [params, setParams] = useState({ whse: 'CPK' });
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    props.onRef(this);
    if (props.data) {
      const data = props.data;
      setData(data);
      setParams({ whse: data.warehouseCode ? data.warehouseCode : 'CPK' });
      formRef.current.setFieldsValue({ model: data });
    }
  }, [props.data]);

  const onFinish = (values: any) => {
    save(values.model);
  };

  const save = (model: any) => {
    let act = 'New';
    const method = 'POST';
    if (model.id) {
      act = 'Modify';
    }
    request(apiURL + act, {
      method,
      data: model,
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success(intl.formatMessage({ id: 'pages.saveSuccess' }));
          props.callback(model.packNum);
        }
        setLoading(false);
      }
    });
  };

  const setCurrent = (item: any) => {
    const model = {
      orderNum: item.OrderNum,
      orderLine: item.OrderLine,
      orderRelNum: item.OrderRelNum,
      partNum: item.PartNum,
      partDescription: item.PartDescription,
      ium: item.IUM,
      ourJobShipQty: item.OurReqQty,
      unitCost: item.UnitPrice,
    };
    formRef.current.setFieldsValue({ model });
  };

  const delObj = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.delete?' }),
      onOk() {
        request(apiURL + 'DelBatch', {
          method: 'POST',
          data: [data.id],
        }).then((response) => {
          if (response) {
            if (response.success) {
              props.callback(data.packNum);
            }
            setLoading(false);
          }
        });
      },
    });
  };

  const whseSugg = () => {
    const data = formRef.current.getFieldsValue();
    request('/api/services/app/PartBin/GetList', {
      method: 'GET',
      params: {
        skipCount: 0,
        maxResultCount: 5,
        keywords: data.model.partNum,
        isEnable: 1,
      },
    }).then((response) => {
      if (response.result.totalCount <= 0) {
        message.warning(intl.formatMessage({ id: 'pages.noStock' }));
        formRef.current.setFieldsValue({
          model: {
            warehouseCode: '',
            binNum: '',
            lotNum: '',
          },
        });
        return;
      }
      const item = response.result.items[0];
      const model = {
        warehouseCode: item.warehouseCode,
        binNum: item.binNum,
        lotNum: item.lotNum,
      };
      formRef.current.setFieldsValue({ model });
    });
  };

  const selectBin = (e: any) => {
    setFreshNum(freshNum + 1);
    setParams({ whse: e });
  };

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 17 },
  };

  return (
    <Form {...layout} ref={formRef} onFinish={onFinish}>
      <Form.Item name={['model', 'id']} hidden={true}>
        <Input />
      </Form.Item>
      <Form.Item label={<FormattedMessage id="pages.packNum" />} style={{ marginBottom: 0 }} required>
        <Input.Group compact>
          <Form.Item
            name={['model', 'packNum']}
            rules={[
              {
                required: true,
                message: <FormattedMessage id="pages.packNum.required" />,
              },
            ]}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item name={['model', 'packLine']} noStyle>
            <InputNumber disabled />
          </Form.Item>
        </Input.Group>
      </Form.Item>

      <Form.Item label={<FormattedMessage id="pages.customer" />} name={['model', 'custNum']} hidden>
        <Input disabled />
      </Form.Item>
      <Form.Item label={<FormattedMessage id="pages.orderNum" />} required>
        <Input.Group compact>
          <Form.Item
            noStyle
            name={['model', 'orderNum']}
            rules={[
              {
                required: true,
                message: intl.formatMessage({id: 'pages.orderNum.required'})
              },
            ]}
          >
            <Input
              style={{ width: 80 }}
              placeholder={intl.formatMessage({ id: 'pages.orderNum' })}
              disabled
            />
          </Form.Item>
          <Form.Item
            noStyle
            name={['model', 'orderLine']}
            rules={[
              { required: true,
                message: intl.formatMessage({id: 'pages.orderLine.required'})
               },
            ]}
          >
            <InputNumber style={{ width: 80 }} disabled />
          </Form.Item>
          <Form.Item
            noStyle
            name={['model', 'orderRelNum']}
            rules={[
              {
                required: true,
                message: intl.formatMessage({id: 'pages.orderRelNum.required'})
              },
            ]}
          >
            <InputNumber style={{ width: 80 }} disabled />
          </Form.Item>
          <Form.Item noStyle>
            <QuerySelect
              width={780}
              sysReportName="SoSearch"
              text={<FormattedMessage id="pages.select" />}
              title={<FormattedMessage id="pages.orderNum" />}
              btntype="primary"
              setCurrent={setCurrent}
              scroll={{ x: 'max-content', y: '200px' }}
              search={{
                filterType: 'light',
              }}
              params={{
                CustNum: data?.custNum,
                OpenOrder: 1,
                VoidOrder: 0,
                Approve: 1,
                OpenRelease: 1,
              }}
            />
          </Form.Item>
        </Input.Group>
      </Form.Item>
      <Form.Item noStyle name={['model', 'unitCost']} hidden>
        <InputNumber />
      </Form.Item>
      <Form.Item label={<FormattedMessage id="pages.partNum" />} required>
        <Input.Group compact>
          <Form.Item
            noStyle
            name={['model', 'partNum']}
            rules={[
              {
                required: true,
                message: <FormattedMessage id="pages.partNum.required" />,
              },
            ]}
          >
            <Input style={{ width: 150 }} disabled />
          </Form.Item>
          <Form.Item noStyle name={['model', 'ium']}>
            <Input style={{ width: 80 }} placeholder="IUM" disabled />
          </Form.Item>
        </Input.Group>
      </Form.Item>
      <Form.Item
        name={['model', 'partDescription']}
        label={<FormattedMessage id="pages.partDescription" />}
        rules={[
          {
            required: true,
            message: <FormattedMessage id="pages.partDescription.required" />,
          },
        ]}
      >
        <Input disabled />
      </Form.Item>
      <Form.Item
        name={['model', 'ourJobShipQty']}
        label={<FormattedMessage id="pages.quantity" />}
        rules={[
          {
            required: true,
            message: <FormattedMessage id="pages.shipQty.required" />,
          },
        ]}
      >
        <InputNumber disabled />
      </Form.Item>
      <Form.Item
        label={<FormattedMessage id="pages.shipLocation" />}
        style={{ marginBottom: 0 }}
        required
        tooltip={intl.formatMessage({ id: 'pages.warehouseTypeIsPassedWhse' })}
      >
        <Input.Group compact>
          <WhseSelect
            width={120}
            showSearch={true}
            rules={[
              {
                required: true,
                message: <FormattedMessage id="pages.warehouseCode.required" />,
              },
            ]}
            name={['model', 'warehouseCode']}
            placeholder={<FormattedMessage id="pages.warehouseCode" />}
            setCurrent={(e: any) => selectBin(e)}
            params={{ wType: 'PassedWhse' }}
          />
          <WhseBinSelect
            width={120}
            rules={[
              {
                required: true,
                message: <FormattedMessage id="pages.binNum.required" />,
              },
            ]}
            showSearch={true}
            name={['model', 'binNum']}
            placeholder={<FormattedMessage id="pages.binNum" />}
            params={params}
            freshNum={freshNum}
          />
          <Form.Item name={['model', 'lotNum']}>
            <Input style={{ width: 80 }} placeholder={intl.formatMessage({ id: 'pages.lotNum' })} />
          </Form.Item>
          <Form.Item>
            <Tooltip title={<FormattedMessage id="pages.binNumSuggest" />}>
              <Button onClick={whseSugg} icon={<BulbOutlined />} type="primary" />
            </Tooltip>
          </Form.Item>
        </Input.Group>
      </Form.Item>
      <Form.Item wrapperCol={{ offset: 5 }} style={{ marginBottom: 0 }}>
        <Input.Group compact>
          <Form.Item name={['model', 'shipCmpl']} valuePropName="checked">
            <Checkbox>
              <FormattedMessage id="pages.shipCmpl" />
            </Checkbox>
          </Form.Item>
          <Form.Item name={['model', 'invoiced']} valuePropName="checked">
            <Checkbox disabled>
              <FormattedMessage id="pages.invoiced" />
            </Checkbox>
          </Form.Item>
        </Input.Group>
      </Form.Item>
      <Form.Item wrapperCol={{ offset: 5 }}>
        <Space>
          <Button key="1" type="primary" htmlType="submit">
            <FormattedMessage id="pages.save" />
          </Button>
          <Button key="2" danger disabled={!data.id} onClick={delObj}>
            <FormattedMessage id="pages.delete" />
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default connect(({ Abp, user }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: user.currentUser,
}))(ViewPage);
